/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worldscale.xp.wslib.im.jabber.impl;

import java.util.Enumeration;
import java.util.Vector;

import net.worldscale.xp.wslib.im.jabber.JabberID;
import net.worldscale.xp.wslib.im.jabber.JabberMessageList;
import net.worldscale.xp.wslib.wsxml.DomUtil;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * 
 * @author Kun
 */
final class ImplMessageList extends JabberMessageList {

	private final Vector<Message> mList = new Vector<Message>();
	private final JabberID mLocalJID;

	public ImplMessageList(JabberID localJID) {
		this.mLocalJID = localJID.getPureJID();
	}

	private static final class MyMessage extends Message {

		private final Element mStanza;
		private final boolean mIsRx;
		private final JabberID mRemoteJID;
		private final JabberID mLocalJID;

		public MyMessage(Element stanza, JabberID localJID) {
			this.mStanza = stanza;
			final JabberID to, from, local;
			local = localJID.getPureJID();
			to = new JabberID(stanza.getAttribute("to"));
			from = new JabberID(stanza.getAttribute("from"));
			if (local.equals(from.getPureJID())) {
				this.mIsRx = false;
				this.mLocalJID = from;
				this.mRemoteJID = to;
			} else if (local.equals(to.getPureJID())) {
				this.mIsRx = true;
				this.mRemoteJID = from;
				this.mLocalJID = to;
			} else {
				throw new RuntimeException("Bad XMPP message.");
			}
		}

		@Override
		public String getBody() {
			final NodeList nl = this.mStanza.getElementsByTagName("body");
			final int len = nl.getLength();
			for (int i = 0; i < len; i++) {
				final Element ele = (Element) nl.item(i);
				return DomUtil.getTextContent(ele);
			}
			return "";
		}

		@Override
		public JabberID getRemoteJID() {
			return this.mRemoteJID;
		}

		@Override
		public Element getStanza() {
			return this.mStanza;
		}

		@Override
		public boolean isRx() {
			return this.mIsRx;
		}

		@Override
		public boolean isTx() {
			return (!this.mIsRx);
		}
	}

	@Override
	public void add(Message msg) {
		if (msg != null) {
			this.mList.addElement(msg);
		}
	}

	@Override
	public void add(Element stanza) {
		this.add(new MyMessage(stanza, this.mLocalJID));
	}

	@Override
	public Message item(int index) {
		return this.mList.elementAt(index);
	}

	@Override
	public JabberMessageList select(Filter filter) {
		final Enumeration<Message> enu = this.mList.elements();
		final ImplMessageList ret = new ImplMessageList(this.mLocalJID);
		for (; enu.hasMoreElements();) {
			final Message msg = enu.nextElement();
			boolean isAccept;
			if (filter == null) {
				isAccept = true;
			} else {
				isAccept = filter.accept(msg);
			}
			if (isAccept) {
				ret.add(msg);
			}
		}
		return ret;
	}

	@Override
	public int size() {
		return this.mList.size();
	}

	@Override
	public JabberID getLocalJID() {
		return mLocalJID;
	}
}
